<template>
    <view>
        <!-- <view class="header">
			<view class="header-c">
				<view class="header-l" @click="selectCity">
					<text class="iconfont icon-zhankai xiala"></text>
					<view class="city-name text-overflow">{{ city }}</view>
				</view>
				<view class="line"></view>
				<image src="../../../static/icon/search.png" mode="" class="search-icon"></image>

				<input type="text" class="input" @input="input" value="" v-model="inputValue" :placeholder="placeholder" placeholder-class="input-class"></input>
				<view class="clear-box" @click="clearInput" v-show="isShowClear"><text class="iconfont icon-qingkong clear-icon"></text></view>
			</view>
		</view> -->
        <!-- 是否开启定位 -->
        <view class="location" v-if="type != '090000'">
            <text class="l text-overflow" @click="goBack">{{ address }}</text>
            <view class="">
                <image src="../../../static/icon/shuaxin.png" class="refresh" mode=""></image>
                <text class="r" @click="openMessage">获取定位</text>
            </view>
        </view>
        <view v-if="env"  class="location mylocation" @click="handle">手动选择</view>
        <!-- 小区街道 -->
        <!-- <view class="address-list" v-if="addressList.length > 0">
      <view
        class="list-item"
        v-for="(item, index) in addressList"
        :key="index"
        @click="
          selectAddress(item.location, item.name, item.cityname, item.pname)
        "
      >
        <view class="title">{{ item.name }}</view>
        <view class="desc"
          >{{ item.cityname }}{{ item.adname }}{{ item.address }}</view
        >
      </view>
    </view> -->
        <uni-popup ref="message" type="center">
            <view class="permission-bc" style="width: 540rpx;height:676rpx">
                <view style="height: 73%;"></view>
                <view @click="getGps" class="d-center" style="height: 78rpx;color: #fff;font-size: 32rpx;">马上开启</view>
                <view @click="closeMessage" class="d-center" style="height: 78rpx;font-size: 28rpx;color: #999999;">以后再说</view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { throttle } from '@/common/js/throttle.js'
import uniPopup from '@/components/uni-ui/uni-popup/uni-popup.vue'
import { keyWordsSearch, aroundSearch } from '@/apis/amap/index.js'
import { getLocation, openGps } from '@/common/js/location.js'
import permision from '@/common/js/permission.js'
export default {
	data() {
		return {
			env: false
		}
	},
	onLoad(option) {
		this.env = process.env.NODE_ENV === 'development' 
        this.getMision()
        console.log(option, '接收的参数是')
        if (option.city) {
            this.city = option.city
            this.location = option.location

            // 用户开启定位获取到的位置仅限
            this.address = option.address

            this.nearSearch()
            this.placeholder = '请输入小区/街道'
        }
        if (option.atte) {
            this.atte = true
        }
        if (option.type) {
            if (option.type == 'nurse') {
                this.type = '090000'
                this.placeholder = '请输入执业机构'
                uni.setNavigationBarTitle({
                    title: '选择职业机构',
                })
            } else {
                this.type = option.type
            }
        }
    },

    onShow() {
        this.type = ''
        let _this = this
        uni.$once('selectCity', function (data) {
            console.log(data)
            _this.city = data
            _this.page = 1
            _this.isReachBottom = false
            if (_this.inputValue) {
                _this.search(_this.inputValue)
            }
        })
    },

    // 下拉刷新
    async onPullDownRefresh() {
        // 页码重置为1
        this.page = 1
        this.isReachBottom = false
        if (this.inputValue) {
            await this.search(this.inputValue)
        }
        uni.stopPullDownRefresh()
    },

    // 触底
    onReachBottom() {
        this.isReachBottom = true
        if (this.isReachBottom) {
            if (this.location) {
                this.page1++
                this.nearSearch()
            } else {
                this.page++
                this.search(this.inputValue)
            }
        }
    },

    data() {
        return {
            loc: -1,
            city: '杭州市', //默认展示杭州
            location: '', //经纬度
            address: '', //详细地理位置
            amapPlugin: null,
            inputValue: '',
            page: 1, //查询页码
            page1: 1, //周边搜索的页码
            addressList: [], //地址列表
            isReachBottom: false, //页面触底了
            type: '', //判断是选择位置 还是职业认证时选择医院
            placeholder: '',
            atte: false, //判断是否为认证时过来获取定位 如果是的话选完位置到首页 不是的话返回上一页,
            timer: null,
        }
    },

    computed: {
        //是否显示清除图标
        isShowClear() {
            return this.inputValue ? true : false
        },
    },

    watch: {
        // 监听输入框值的变化-对应的触底的页码更新
        inputValue(newValue, oldValue) {
            console.log(newValue, oldValue, '输入框的值是')
            if (newValue !== oldValue) {
                this.page = 1 //页码置为1（比如分页请求此时page为5，此时修改了关键字，page要为1）
                this.isReachBottom = false
                if (newValue) {
                    this.search(newValue)
                } else {
                    this.addressList = []
                }
            }
        },
        // 监听城市变化
        city(newValue, oldValue) {
            if (newValue !== oldValue) {
                // 经纬度、地址、
                this.page = 1 //页码置为1（比如分页请求此时page为5，此时修改了关键字，page要为1）
                this.isReachBottom = false
                if (newValue) {
                    if (!this.inputValue) {
                        this.addressList = []
                        return
                    }
                    this.search(this.inputValue)
                }
            }
        },
    },
    components: {
        uniPopup,
    },
    methods: {
        async getMision() {
            if (uni.getSystemInfoSync().platform == 'android') {
                // 安卓权限查询
                this.loc = await permision.checkAndroidSelfPermission(
                    'android.permission.ACCESS_FINE_LOCATION'
                )
                console.log('anzhuo', this.loc)
            }
        },
        openMessage() {
            let that = this
            if (this.loc == -1) {
                that.$refs.message.open()
            } else {
                that.getGps()
            }
        },
        closeMessage() {
            this.$refs.message.close()
        },
        getGps() {
            let that = this
            if (that.loc == -1) {
                this.closeMessage()
            }
            if (!this.timer) {
                this.timer = setTimeout(() => {
                    // 需要更新经纬度
                    getLocation(true)
                    // 其实也可以使用store中的计算属性getters
                    that.address = that.$store.state.address
                    if (that.$store.state.city) {
                        that.city = that.$store.state.city
                    }
                    that.location =
                        that.$store.state.latitude +
                        ',' +
                        that.$store.state.longitude
                    clearTimeout(that.timer)
                    console.log('that.location', that.location)
                }, 30)
            }
        },
        handle() {
            uni.navigateTo({
                url: '/pages/address/input-address/index',
            })
        },
        selectCity() {
            uni.navigateTo({
                url: '../select-city/select-city',
            })
        },
        // 选择地址
        selectAddress(location, address, city, pname) {
            console.log(location, address, city, pname, '0000')
            let my = pname + city + address
            if (this.type) {
                if (this.type != '090000') {
                    uni.$emit(this.type, {
                        my,
                    })
                } else {
                    uni.$emit('nurseMechanism', {
                        location: location,
                        address: address,
                        city: city,
                    })
                }
                this.clearInput()
                uni.navigateBack({
                    delta: 1,
                })
            } else {
                this.$store.commit('setLatitude', '')
                this.$store.commit('setLongitude', '')
                this.$store.commit('setAddress', '')
                this.$store.commit('setCity', '')
                let res = location.split(',')
                // console.log(res,'jieguoshisha')
                try {
                    console.log(location, my, '9999')
                    this.$store.commit('setAddress', my)
                    this.$store.commit('setLatitude', res[1])
                    this.$store.commit('setLongitude', res[0])
                    this.$store.commit('setCity', city)
                    // this.$store.dispatch('updateAddress',item.pname+item.cityname+item.adname+item.address)
                    // if(this.atte){
                    // 	uni.switchTab({
                    // 		url:'../../tabbars/index/index'
                    // 	})
                    // }else{
                    uni.navigateBack({
                        delta: 1,
                    })
                    // }
                } catch (e) {
                    console.log('err99999999------', e)
                }

                // #ifdef APP
                plus.nativeUI.toast('地理位置更新成功~')
                // #endif
            }
        },
        clearInput() {
            this.inputValue = ''
            this.addressList = []
        },
        input: throttle(function (e) {
            let _this = this
            // 根据城市查询周边
            if (e.target.value) {
                _this.search(e.target.value)
            }
        }, 300),

        async search(e) {
            if (!e) return //为空的时候，已有地址选择其他地址……
            let data = {
                keywords: e,
                city: this.city, //查询当前城市
                citylimit: true, //返回仅限当前城市下的地址
                page: this.page,
                offset: 15, //每页记录数据
            }
            let res = await keyWordsSearch(data)
            if (res.data.pois.length > 0) {
                if (this.isReachBottom) {
                    this.addressList.push(...res.data.pois)
                } else {
                    this.addressList = res.data.pois
                }
            } else {
                this.isReachBottom = false
            }
        },
        // 周边搜索
        async nearSearch() {
            // 周边搜搜,也就有经纬度的时候查询下
            // #ifdef APP-PLUS
            plus.nativeUI.showWaiting()
            // #endif
            let data = {
                location: this.location, //定位
                city: this.city,
                page: this.page1,
                extensions: 'base',
            }
            let res = await aroundSearch(data)
			console.log("出发=======2222",res)
            if (res.data.pois.length > 0) {
                if (this.isReachBottom) {
                    this.addressList.push(...res.data.pois)
                } else {
                    this.addressList = res.data.pois
                }
            } else {
                this.isReachBottom = false
            }
            // #ifdef APP-PLUS
			console.log("出发=======")
            plus.nativeUI.closeWaiting()
            // #endif
        },

        goBack() {
            uni.navigateBack({
                delta: 1,
            })
        },
    },
}
</script>

<style lang="less" scoped>
.header {
    width: 670rpx;
    position: sticky;
    top: 0;
    /* #ifdef APP */
    top: 0;
    /* #endif */
    background-color: #ffffff;
    font-family: PingFangSC-Medium, PingFang SC;
    padding: 24rpx 40rpx;
    font-size: 32rpx;
    z-index: 9999;

    .header-c {
        height: 84rpx;
        display: flex;
        align-items: center;
        padding: 0 16rpx;
        background: #ffffff;
        border-radius: 20rpx;
        border: 4rpx solid #3c8eff;
        box-sizing: border-box;

        .header-l {
            display: flex;
            align-items: center;

            .xiala {
                font-size: 48rpx;
                vertical-align: middle;
            }

            .city-name {
                max-width: 126rpx;
                font-weight: 500;
                color: rgba(0, 0, 0, 0.87);
                margin-right: 24rpx;
            }
        }

        .search-icon {
            width: 48rpx;
            height: 48rpx;
        }

        .line {
            width: 1rpx;
            height: 40rpx;
            background-color: rgba(0, 0, 0, 0.1);
            margin-right: 16rpx;
        }

        .input {
            margin-left: 8rpx;
        }

        .clear-box {
            width: 48rpx;
            height: 48rpx;
            margin-left: auto;

            .clear-icon {
                color: #cccccc;
                font-size: 32rpx;
                line-height: 32rpx;
            }
        }
    }

    .input-class {
        font-size: 32rpx;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.38);
    }
}

.location {
    height: 120rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 40rpx;
    font-size: 28rpx;
    border-bottom: solid 1rpx rgba(0, 0, 0, 0.1);
    font-weight: 400;
    box-sizing: border-box;

    .refresh {
        width: 24rpx;
        height: 24rpx;
        vertical-align: middle;
        margin-right: 10rpx;
    }

    .l {
        color: rgba(0, 0, 0, 0.38);
        max-width: 420rpx;
    }

    .r {
        color: #666666;
    }
}

.address-list {
    padding: 0 40rpx;

    .list-item {
        padding: 16rpx 0;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        border-bottom: solid 1rpx rgba(0, 0, 0, 0.1);

        .title {
            font-size: 28rpx;
            color: #333333;
        }

        .desc {
            font-size: 24rpx;
            color: #666666;
            margin-top: 6rpx;
        }
    }
}

.mylocation {
    display: flex;
    flex-direction: row-reverse;
    color: #666;
}
.permission-bc {
    background-image: url('http://loto.oss-cn-shanghai.aliyuncs.com/email/69561dce4c194907.png');
    background-size: 100%;
    background-repeat: no-repeat;
}
</style>